package com.muchen.partnermatching.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.muchen.partnermatching.common.BaseResponse;
import com.muchen.partnermatching.common.ErrorCode;
import com.muchen.partnermatching.common.ResultUtils;
import com.muchen.partnermatching.exception.BusinessException;
import com.muchen.partnermatching.model.domain.Team;
import com.muchen.partnermatching.model.domain.User;
import com.muchen.partnermatching.model.domain.UserTeam;
import com.muchen.partnermatching.model.dto.TeamQuery;
import com.muchen.partnermatching.model.request.*;
import com.muchen.partnermatching.model.vo.TeamUserVO;
import com.muchen.partnermatching.service.TeamService;
import com.muchen.partnermatching.service.UserService;
import com.muchen.partnermatching.service.UserTeamService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;


/**
 * @author mu-chen
 * @create 2024-09-23 23:16
 * @Description
 */
@RestController
@RequestMapping("/team")
@CrossOrigin(origins = "http://localhost:5173/", allowCredentials = "true")
//@CrossOrigin(origins = "http://www.muchen-demo.cn/", allowCredentials = "true")
@Slf4j
public class TeamController {

    @Resource
    private TeamService teamService;

    @Resource
    private UserService userService;

    @Resource
    private UserTeamService userTeamService;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @CrossOrigin
    @PostMapping("/add")
    public BaseResponse<Long> addTeam(@RequestBody TeamAddRequest teamAddRequest, HttpServletRequest request) {
        if (teamAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_NULL_ERROR);
        }
        User currentUser = userService.getCurrentUser(request);
        Team team = new Team();
        BeanUtils.copyProperties(teamAddRequest, team);
        long teamId = teamService.addTeam(team, currentUser);
        return ResultUtils.success(teamId);
    }

    @CrossOrigin
    @PostMapping("/update")
    public BaseResponse<Boolean> updateTeam(@RequestBody TeamUpdateRequest teamUpdateRequest, HttpServletRequest request) {
        if (teamUpdateRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User currentUser = userService.getCurrentUser(request);
        boolean result = teamService.updateTeam(teamUpdateRequest, currentUser);
        if (!result) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "更新失败");
        }
        return ResultUtils.success(true);
    }

    @CrossOrigin
    @GetMapping("/get")
    public BaseResponse<Team> getTeamById(long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Team team = teamService.getById(id);
        if (team == null) {
            throw new BusinessException(ErrorCode.PARAMS_NULL_ERROR);
        }
        return ResultUtils.success(team);
    }

    /**
     * 队伍列表
     * @param teamQuery
     * @return
     */
    @CrossOrigin
    @GetMapping("/list")
    public BaseResponse<List<TeamUserVO>> listTeams(TeamQuery teamQuery, HttpServletRequest request){
        if (teamQuery == null){
            throw new BusinessException(ErrorCode.PARAMS_NULL_ERROR);
        }

        boolean isAdmin = userService.isAdmin(request);
        // 1. 查询队伍列表
        List<TeamUserVO> teamList = teamService.listTeams(teamQuery, isAdmin);
        final List<Long> teamIdList = teamList.stream().map(TeamUserVO::getId).collect(Collectors.toList());
        // 2. 判断当前用户是否已加入队伍
        QueryWrapper<UserTeam> userTeamQueryWrapper = new QueryWrapper<>();
        try {
            User currentUser = userService.getCurrentUser(request);
            userTeamQueryWrapper.eq("userId", currentUser.getId());
            userTeamQueryWrapper.in("teamId", teamIdList);
            List<UserTeam> userTeamList = userTeamService.list(userTeamQueryWrapper);
            // 已加入的队伍 id 集合、
            Set<Long> hasJoinTeamIdSet = userTeamList.stream().map(UserTeam::getTeamId).collect(Collectors.toSet());
            teamList.forEach(team -> {
                boolean hasJoin = hasJoinTeamIdSet.contains(team.getId());
                team.setHasJoin(hasJoin);
            });
        } catch (Exception e) {}
        // 3. 查询已加入队伍的人数
        QueryWrapper<UserTeam> userTeamJoinQueryWrapper = new QueryWrapper<>();
        userTeamJoinQueryWrapper.in("teamId", teamIdList);
        List<UserTeam> userTeamList = userTeamService.list(userTeamJoinQueryWrapper);
        // 队伍id => 加入这个队伍的用户列表
        Map<Long, List<UserTeam>> teamIdUserTeamList = userTeamList.stream().collect(Collectors.groupingBy(UserTeam::getTeamId));
        teamList.forEach(team -> team.setHasJoinNum(teamIdUserTeamList.getOrDefault(team.getId(), new ArrayList<>()).size()));
        return ResultUtils.success(teamList);
    }

    /**
     * 队伍列表分页
     * @param teamQuery
     * @return
     */
    @CrossOrigin
    @GetMapping("/list/page")
    public BaseResponse<Page<Team>> listTeamsByPage(TeamQuery teamQuery){
        if (teamQuery == null){
            throw new BusinessException(ErrorCode.PARAMS_NULL_ERROR);
        }
        Team team = new Team();
        BeanUtils.copyProperties(teamQuery, team);
        Page<Team> page = new Page<>(teamQuery.getPageNum(),teamQuery.getPageSize());
        QueryWrapper<Team> queryWrapper = new QueryWrapper<>(team);
        Page<Team> resultPage = teamService.page(page, queryWrapper);
        return ResultUtils.success(resultPage);
    }

    @CrossOrigin
    @PostMapping("/join")
    public BaseResponse<Boolean> joinTeam(@RequestBody TeamJoinRequest teamJoinRequest, HttpServletRequest request){
        if (teamJoinRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_NULL_ERROR);
        }
        User currentUser = userService.getCurrentUser(request);
        boolean result = teamService.joinTeam(teamJoinRequest, currentUser);
        return ResultUtils.success(result);
    }

    @CrossOrigin
    @PostMapping("/quit")
    public BaseResponse<Boolean> quitTeam(@RequestBody TeamQuitRequest teamQuitRequest, HttpServletRequest request){
        if (teamQuitRequest == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User currentUser = userService.getCurrentUser(request);
        boolean result = teamService.quitTeam(teamQuitRequest, currentUser);
        return ResultUtils.success(result);
    }

    @CrossOrigin
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteTeam(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long id = deleteRequest.getId();
        User currentUser = userService.getCurrentUser(request);
        boolean result = teamService.deleteTeam(id, currentUser);
        if (!result) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "删除失败");
        }
        return ResultUtils.success(true);
    }

    /**
     * 获取当前用户创建的队伍
     * @param teamQuery
     * @param request
     * @return
     */
    @CrossOrigin
    @GetMapping("/list/my/create")
    public BaseResponse<List<TeamUserVO>> listMyCreateTeams(TeamQuery teamQuery, HttpServletRequest request) {
        // 判断teamQuery是否为空，如果为空则抛出异常
        if (teamQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_NULL_ERROR);
        }

        // 获取当前用户
        User currentUser = userService.getCurrentUser(request);
        // 设置teamQuery中的userId为当前用户的id
        teamQuery.setUserId(currentUser.getId());
        // 调用teamService的listTeams方法，获取teamList
        List<TeamUserVO> teamList = teamService.listTeams(teamQuery, true);
        if (teamList.size() == 0) {
            return ResultUtils.error(ErrorCode.PARAMS_NULL_ERROR, "未创建任何队伍");
        }
        final List<Long> teamIdList = teamList.stream().map(TeamUserVO::getId).collect(Collectors.toList());

        // 3. 查询已加入队伍的人数
        QueryWrapper<UserTeam> userTeamJoinQueryWrapper = new QueryWrapper<>();
        userTeamJoinQueryWrapper.in("teamId", teamIdList);
        List<UserTeam> userTeamList = userTeamService.list(userTeamJoinQueryWrapper);
        // 队伍id => 加入这个队伍的用户列表
        Map<Long, List<UserTeam>> teamIdUserTeamList = userTeamList.stream().collect(Collectors.groupingBy(UserTeam::getTeamId));
        teamList.forEach(team -> team.setHasJoinNum(teamIdUserTeamList.getOrDefault(team.getId(), new ArrayList<>()).size()));

        // 返回teamList
        return ResultUtils.success(teamList);
    }

    /**
     * 获取当前用户加入的队伍
     * @param teamQuery
     * @param request
     * @return
     */
    @CrossOrigin
    @GetMapping("/list/my/join")
    public BaseResponse<List<TeamUserVO>> listMyJoinTeams(TeamQuery teamQuery, HttpServletRequest request) {
        // 判断teamQuery是否为空，如果为空则抛出异常
        if (teamQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_NULL_ERROR);
        }

        // 获取当前用户
        User currentUser = userService.getCurrentUser(request);
        // 创建查询条件
        QueryWrapper<UserTeam> queryWrapper = new QueryWrapper<>();
        // 查询条件：用户id等于当前用户的id
        queryWrapper.eq("userId", currentUser.getId());
        // 根据查询条件查询用户队伍列表
        List<UserTeam> userTeamList = userTeamService.list(queryWrapper);

        if (userTeamList.size() == 0) {
            return ResultUtils.error(ErrorCode.PARAMS_NULL_ERROR, "未加入任何队伍");
        }
        // 取出不重复的队伍id
        // 将用户队伍列表按照队伍id进行分组
        Map<Long, List<UserTeam>> listMap = userTeamList.stream().collect(Collectors.groupingBy(UserTeam::getTeamId));
        // 获取队伍id列表
        List<Long> idList = new ArrayList<>(listMap.keySet());
        // 将队伍id列表设置到队伍查询条件中
        teamQuery.setIdList(idList);
        // 根据队伍查询条件查询队伍列表
        List<TeamUserVO> teamList = teamService.listTeams(teamQuery, true);

        final List<Long> teamIdList = teamList.stream().map(TeamUserVO::getId).collect(Collectors.toList());
        // 3. 查询已加入队伍的人数
        QueryWrapper<UserTeam> userTeamJoinQueryWrapper = new QueryWrapper<>();
        userTeamJoinQueryWrapper.in("teamId", teamIdList);
        List<UserTeam> userTeamJoinList = userTeamService.list(userTeamJoinQueryWrapper);
        // 队伍id => 加入这个队伍的用户列表
        Map<Long, List<UserTeam>> teamIdUserTeamList = userTeamJoinList.stream().collect(Collectors.groupingBy(UserTeam::getTeamId));
        teamList.forEach(team -> team.setHasJoinNum(teamIdUserTeamList.getOrDefault(team.getId(), new ArrayList<>()).size()));

        // 返回队伍列表
        return ResultUtils.success(teamList);
    }
}
